/*
 * @Description: 备份数据库
 * @Author: lihk
 * @Date: 2024-09-26 13:40:46
 */
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { exec } from 'child_process';

@Injectable()
export class BackupService {
  private readonly DB_USERNAME: string;
  private readonly DB_PASSWORD: string;
  private readonly DB_DATABASE: string;
  constructor(private configService: ConfigService) {
    this.DB_USERNAME = this.configService.get<string>('DB_USERNAME');
    this.DB_PASSWORD = this.configService.get<string>('DB_PASSWORD');
    this.DB_DATABASE = this.configService.get<string>('DB_DATABASE');
  }

  private getTimestamp(): string {
    const now = new Date();
    const timestamp = now.getFullYear() + '-' +
      ('0' + (now.getMonth() + 1)).slice(-2) + '-' +
      ('0' + now.getDate()).slice(-2) + '_' +
      ('0' + now.getHours()).slice(-2) + '-' +
      ('0' + now.getMinutes()).slice(-2) + '-' +
      ('0' + now.getSeconds()).slice(-2);
    return timestamp;
  }
  backupDatabase() {
    return new Promise((resolve, reject) => {
      exec(
        `docker exec mysql mysqldump -u ${this.DB_USERNAME} -p${this.DB_PASSWORD} ${this.DB_DATABASE} > ${this.getTimestamp()}.sql`,
        (error, stdout) => {
          if (error) {
            reject(error);
          } else {
            resolve(stdout);
          }
        },
      );
    });
  }
}